﻿using AduSkin.Controls.Metro;
using HsServerHa.Core.Http;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.HttpHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Windows;
using System.Windows.Controls;

namespace HsServerHa.UserControls
{
    /// <summary>
    /// JoinMaster.xaml 的交互逻辑
    /// </summary>
    public partial class JoinMaster : UserControl
    {
        public JoinMaster()
        {
            InitializeComponent();
            this.CurrIP.Text = App.CurrIP?.ToString();
        }

        private async void btn_Setting_Click(object sender, RoutedEventArgs e)
        {

            if (!NetWorkHelper.ValidateIpAddress(this.MasterIP.Text))
            {
                AduMessageBoxs.Show("请输入合法的IP地址");
                return;
            }
            this.Dispatcher.Invoke(new Action(async() => {
                MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定计入主机:{this.MasterIP.Text}吗？", "系统提示!", "确定", "取消");
                if (dr == MessageBoxResult.OK)
                {
                    var masterPath = $"http://{MasterIP.Text}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                    //访问主机是否存在
                    //请求主机的接口，是否存在数据
                    var result = await HttpHelpers.Get<HttpResponseResultModel<MasterSlaveBindEntity>>($"{masterPath}{ConfigurationManager.AppSettings["getMasterInfo"]?.ToString() ?? "getMasterInfo"}");

                    if (result.IsSuccess)
                    {
                        //推送从机IP到主机
                        var pushResult = await HttpHelpers.PostToJson<HttpResponseResultModel<MasterSlaveBindEntity>>(masterPath
                            + ConfigurationManager.AppSettings["postSlaveInfo"]?.ToString() ?? "postSlaveInfo", JsonConvert.SerializeObject(new MasterSlaveBindEntity
                            {
                                SlaveIP = CurrIP.Text
                            }));
                        if (pushResult.IsSuccess)
                        {
                            MasterSlaveBindEntity remote = result.BackResult;
                            SQLiteHelper.ExecuteSql("delete from MasterSlaveBind");

                            var IsInsertSuccess = DbHelperSQLite.ExecuteSql($"insert into  MasterSlaveBind (MasterIP,SlaveIP,IsMaster,VirtuallyIP,CreateTime)  values('{this.MasterIP.Text}','{this.CurrIP.Text}','false','{remote.VirtuallyIP}','{DateTime.Now.ToString()}') ");
                            SQLiteHelper.ExecuteSql($"update VirtuallyManage set VirtuallyIP='{remote.VirtuallyIP}'");
                            if (IsInsertSuccess <= 0)
                            {
                                LoggerHelper.SetInfo("加入主机失败->数据存储失败", "加入主机");
                                AduMessageBoxs.Show("加入失败！");
                                return;
                            }
                            App.MasterIP = MasterIP.Text;


                            //调用主机Http接口，直接上传从机IP数据

                            AduMessageBoxs.Show("加入成功！");
                            LoggerHelper.SetInfo("加入主机成功", "加入主机");
                            var control = this.Parent as ContentControl;
                            Window win = Window.GetWindow(control);
                            var title = win?.Title;
                            if (title != null)
                            {
                                if (title != "HsServerHa")
                                {
                                    win.Close();
                                }

                            }
                        }
                        else
                        {
                            AduMessageBoxs.Show("远程主机异常！");
                            LoggerHelper.SetInfo("加入主机失败->远程主机异常", "加入主机");
                            return;
                        }

                    }
                    else
                    {
                        AduMessageBoxs.Show("主机不存在！");
                        LoggerHelper.SetInfo("加入主机失败->主机不存在", "加入主机");
                    }
                }

            }));

        


        }
    }
}
